package com.cmcc.passenger.ui.main

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cmcc.passenger.data.AppRequest
import com.cmcc.passenger.data.Network
import com.cmcc.passenger.data.PassDataRepository
import com.cmcc.passenger.data.entity.response.*
import com.cmcc.shared.Event
import com.cmcc.shared.SdkManager
import com.cmcc.shared.model.AppResponse
import com.cmcc.shared.utils.L
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class CallCarViewModel : ViewModel() {

    private val _directionStartSelector = MutableLiveData<Event<Unit>>()
    private val _directionEndSelector = MutableLiveData<Event<Unit>>()
    private val _moreOptionSelector = MutableLiveData<Event<Unit>>()
    private val _meSelector = MutableLiveData<Event<Unit>>()
    private val _nextStepSelector = MutableLiveData<Event<Unit>>()
    val geoLocation = MutableLiveData<String>()

    val createOrder = MutableLiveData<AppResponse<CreateOrderResponse>>()

    val direction = MutableLiveData<String>()
    val googleDirection = MutableLiveData<Direction>()

    val processOrder = MutableLiveData<OrderRecord>()

    val noRouters = MutableLiveData<Boolean>()

    val passengerInfo = MutableLiveData<PassengerInfo>()

    val orderFee = MutableLiveData<OrderFee>()


    /**
     * 创建订单
     */
    fun createOrder(order: OrderRecord?) {
        viewModelScope.launch(Dispatchers.Main) {

                val response = AppRequest.getInstance().createOrder(order)
                if (response.isSuccessful) {
                    val posts = response.body()
                    createOrder.value = posts
                } else {
                    L.d("123")
                }

        }
    }

    /**
     * 查询正在进行的订单
     */
    fun queryOrderProgress() {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = AppRequest.getInstance().queryOrderInProgress()
                if (response.isSuccessful) {
                    val post = response.body()
                    processOrder.value = post?.data
                } else {
                    L.d("server error")
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    fun getRemarks() {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = AppRequest.getInstance().getRemarks()
                if (response.isSuccessful) {
                    val data = response.body()
                    PassDataRepository.getInstance().getRemarks().value = data?.data
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    /**
     *
     * 获取更多出行选项列表。
     */
    fun getTravelList() {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = AppRequest.getInstance().getTravelItemList()
                if (response.isSuccessful) {
                    response.body()?.data?.let {
                        PassDataRepository.getInstance().getTunnels().value = it.tunnels
                        PassDataRepository.getInstance().getCarCategories().value = it.vehicleTypes
                        PassDataRepository.getInstance().getTips().value = it.gratuityItems
                        PassDataRepository.getInstance().getRemarks().value = it.remakes
                    }
                } else {

                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }



    fun getPassengerInfo() {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = AppRequest.getInstance().getPassengerInfo()
                if (response.isSuccessful) {
                    val data = response.body()
                    passengerInfo.value = data?.data
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    fun getTunnel(): MutableLiveData<List<Tunnel>> {
        return PassDataRepository.getInstance().getTunnels()
//        viewModelScope.launch(Dispatchers.Main) {
//            try {
//                val response = AppRequest.getInstance().getTunnel()
//                if (response.isSuccessful) {
//                    val posts = response.body()
//                    PassDataRepository.getInstance().getTunnels().value = posts?.data
//                } else {
//                    L.d("123")
//                }
//            } catch (e: Exception) {
//                L.d("e :" + e.message + "," + e.cause)
//            }
//        }
    }

    fun getGratuity(): MutableLiveData<List<Gratuity>> {
        return PassDataRepository.getInstance().getTips()

//        viewModelScope.launch(Dispatchers.Main) {
//            try {
//                val response = AppRequest.getInstance().getGratuity()
//                if (response.isSuccessful) {
//                    val posts = response.body()
//                    PassDataRepository.getInstance().getTips().value = posts?.data
//                } else {
//                    L.d("123")
//                }
//            } catch (e: Exception) {
//                L.d("e :" + e.message + "," + e.cause)
//            }
//        }
    }

    fun getStations(): MutableLiveData<List<Station>> {
        return PassDataRepository.getInstance().getStations()
    }

    fun getCarCategory(): MutableLiveData<List<CarCategory>> {

        return PassDataRepository.getInstance().getCarCategories()
//
//        viewModelScope.launch(Dispatchers.Main) {
//            try {
//                val response = AppRequest.getInstance().getCarCategory()
//                if (response.isSuccessful) {
//                    val posts = response.body()
//                    PassDataRepository.getInstance().getCarCategories().value = posts?.data
//                } else {
//                    L.d("123")
//                }
//            } catch (e: Exception) {
//                L.d("e :" + e.message + "," + e.cause)
//            }
//        }
    }

//    fun locate(latLng: LatLng) {
//        viewModelScope.launch(Dispatchers.Main) {
//            val postRequest = Network.getInstance().appApiService.nearbyOrder(latLng.latitude.toString(),latLng.longitude.toString(),100.toString())
//            try {
//                val response = postRequest.await()
//                if (response.isSuccessful) {
//                    val posts = response.body()
//                    L.d(posts?.code.toString()+"<"+posts?.data)
//                } else {
//                    L.d("123")
//                }
//            } catch (e: Exception) {
//                L.d("e :" + e.message + "," + e.cause)
//            }
//        }
//
//    }

    fun geocode(lat: Double, lng: Double) {
        viewModelScope.launch(Dispatchers.Main) {
            val postRequest = Network.getInstance().googleApiService.geocode("$lat,$lng")
            try {
                val response = postRequest.await()
                if (response.isSuccessful) {
                    val posts = response.body()
                    if (!posts?.results.isNullOrEmpty()) {
                        L.d(posts.toString())
                        geoLocation.value =
                            posts?.results?.get(0)?.address_components?.get(0)?.long_name
                    }
                } else {
                    L.d(response.errorBody().toString())
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    fun getDirection(origin: String, destination: String) {
        viewModelScope.launch(Dispatchers.Main) {
            val postRequest =
                Network.getInstance().googleApiService.getDirection(origin, destination)
            try {
                val response = postRequest.await()
                if (response.isSuccessful) {
                    val posts = response.body()
                    if (!posts?.routes.isNullOrEmpty()) {
                        googleDirection.value = Direction(
                            posts?.routes?.get(0)?.legs?.get(0)?.distance?.text,
                            posts?.routes?.get(0)?.legs?.get(0)?.duration?.text,
                            posts?.routes?.get(0)?.legs?.get(0)?.distance?.value ?: 0,
                            posts?.routes?.get(0)?.legs?.get(0)?.duration?.value ?: 0
                        )

                        direction.value = posts?.routes?.get(0)?.overview_polyline?.points
                        noRouters.value = false
                    } else {
                        noRouters.value = true
                    }
                } else {
                    L.d(response.errorBody().toString())
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    /**
     * 计算费用
     * mileage：公里数
     * duration：预计时间
     * tunnelId：隧道
     * carCategoryId：车种
     */
    fun computationFee(
        mileage: Double,
        tunnelCode: String,
        vehicleTypeCode: String
    ) {
        viewModelScope.launch(Dispatchers.Main) {
            val response =
                AppRequest.getInstance().computationFee(mileage, tunnelCode, vehicleTypeCode)

            try {
                if (response.isSuccessful) {
                    val posts = response.body()
                    orderFee.value = posts?.data
                } else {
                    L.d(response.errorBody().toString())
                }
            } catch (e: Exception) {
                L.d("e :" + e.message + "," + e.cause)
            }
        }
    }

    fun directionStartSelector(): LiveData<Event<Unit>> {
        return _directionStartSelector
    }

    fun directionEndSelector(): LiveData<Event<Unit>> {
        return _directionEndSelector
    }

    fun moreOptionSelector(): LiveData<Event<Unit>> {
        return _moreOptionSelector
    }

    fun meSelector(): LiveData<Event<Unit>> {
        return _meSelector
    }

    fun nextStepSelector(): LiveData<Event<Unit>> {
        return _nextStepSelector
    }

    fun onDirectionStartClick() {
        _directionStartSelector.value = Event(Unit)
    }

    fun onDirectionEndClick() {
        _directionEndSelector.value = Event(Unit)
    }

    fun onMoreOptionsClick() {
        _moreOptionSelector.value = Event(Unit)
    }

    fun onMeClick() {
        _meSelector.value = Event(Unit)
    }

    fun nextStepClick() {
        _nextStepSelector.value = Event(Unit)
    }


}
